# Force Bash
SHELL := /bin/bash

ifeq ($(DESTDIR),)
	DESTDIR := /
endif

ifeq ($(PREFIX),)
	PREFIX := usr/
endif

LC_SRC = ./locale

# Locale .po sources
LC_SOURCES := $(shell find $(LC_SRC) -name '*.po')

# Locale .mo bins
LC_OBJECTS := $(shell find $(LC_SRC) -name '*.mo')
LC_INSTALL := $(patsubst $(LC_SRC)/%,%,$(LC_OBJECTS))

# Theme .qrc icon sources
QRC_SOURCES := $(shell find ./themes -name '*.qrc')

# Docs
DOC_INSTALL += "README.md" "COPYING" "CHANGELOG.md" "docs/index.html" \
				"docs/index.rst" "docs/style.css"

DOC_IMG_INSTALL := $(foreach dir,docs, $(wildcard $(dir)/images/*.png))

# Schema files
SCHEMA_INSTALL = "data/schema/searxng_config.json" \
					"data/schema/searxng_query.json" \
					"data/schema/searx_space_instances.json"


.PHONY : all
all: wheel locale themes


.PHONY : wheel
wheel: $(LC_SOURCES)
	@python3 -m build --wheel --no-isolation


.PHONY : locale
locale: $(LC_SOURCES)
	@utils/locale_tool.sh -m all


.PHONY : themes
themes: $(QRC_SOURCES)
	@python3 utils/themes_tool.py make all


.PHONY : install
install:
	# INSTALL: The Searx-Qt Python package
	@python3 -m installer --destdir $(DESTDIR) dist/*.whl

	# INSTALL: Locales
	@for lc in $(LC_INSTALL) ; do \
		pathname=$$(dirname $$lc); \
		mkdir -p "$(DESTDIR)/$(PREFIX)/share/locale/$$pathname"; \
		cp "$(LC_SRC)/$$lc" "$(DESTDIR)/$(PREFIX)/share/locale/$$pathname"; \
	done

	# INSTALL: Themes
	@themes=$$(python3 utils/themes_tool.py list); \
	for theme in $${themes[@]} ; do \
		themepath="$(DESTDIR)/$(PREFIX)/share/searx-qt/themes/$${theme}"; \
		mkdir -p "$${themepath}"; \
		files=$$(python3 utils/themes_tool.py files $${theme}); \
		for file in $${files} ; do \
			cp "$${file}" "$${themepath}"; \
		done; \
	done

	# INSTALL: Docs
	@docdir="$(DESTDIR)/$(PREFIX)/share/doc/searx-qt"; \
	mkdir -p "$${docdir}"; \
	for file in $(DOC_INSTALL) ; do \
		cp "$${file}" "$${docdir}"; \
	done; \
	mkdir -p "$${docdir}/images"; \
	for file in $(DOC_IMG_INSTALL) ; do \
		cp "$${file}" "$${docdir}/images"; \
	done

	# INSTALL: Bin
	@mkdir -p "$(DESTDIR)/$(PREFIX)/bin/"
	@cp bin/searx-qt "$(DESTDIR)/$(PREFIX)/bin/"

	# INSTALL: Desktop
	@mkdir -p "$(DESTDIR)/$(PREFIX)/share/applications/"
	@cp share/searx-qt.desktop "$(DESTDIR)/$(PREFIX)/share/applications/"

	# INSTALL: Schemas
	@schemadir="$(DESTDIR)/$(PREFIX)/share/searx-qt/schema"; \
	mkdir -p "$${schemadir}"; \
	for file in $(SCHEMA_INSTALL) ; do \
		cp "$${file}" "$${schemadir}"; \
	done


.PHONY : clean
clean: dist build
	@rm -rf dist
	@rm -rf build
